#include <PA9.h>

#include "Constants.h"
#include "Control.h"

namespace BlobSalladDS
{
	Control::Control()
	{
		this->env = new Environment(0.2, 0.2, 2.6, 1.8);
		this->scaleFactor = 200;
		this->blobColl = new BlobCollective(1, 1, 1, 10);
		this->gravity = new Vector(0, 10);
		this->stopped = false;
	}

	void Control::toggleGravity()
	{
		if(gravity->getY() > 0.0)
		{
			gravity->setY(0.0);
		}
		else
		{
			gravity->setY(10.0);
		}
	}

	void Control::clearScreen()
	{
		// white
		u16 background = PA_RGB(31, 31, 31);

		for (int i = 0; i < NDS_SCREEN_WIDTH; i++)
		{
			for (int j = 0; j < NDS_SCREEN_HEIGHT; j++)
			{
				PA_Put16bitPixel(SCREEN_BOTTOM, i, j, background);
			}
		}
	}

	void Control::start()
	{
		this->stopped = false;
		this->timeout();
	}

	void Control::stop()
	{
		this->stopped = true;
	}

	void Control::timeout()
	{
		// reinitialise graphics on bottom screen
		PA_Init16bitBg(SCREEN_BOTTOM, 3);

		while (true)
		{
			this->draw();
			this->update();

			if (this->stopped == false)
			{
				break;
			}

			//PA_Draw();
			PA_WaitForVBL();
		}
	}

	void Control::draw()
	{
		//var canvas = document.getElementById('blob');

		//if (canvas.getContext == null)
		//{
		//	return;
		//}

		//var ctx = canvas.getContext('2d');

		//ctx.clearRect(0, 0, width, height);
		this->clearScreen();

		//this->env->draw(NULL, this->scaleFactor);
		this->blobColl->draw(NULL, this->scaleFactor);
	}

	void Control::update()
	{
		double dt = 0.05;

		//if (savedMouseCoords != NULL && selectOffset != NULL)
		//{
			//this->blobColl->selectedBlobMoveTo(
			//	this->savedMouseCoords.x - this->selectOffset.x,
			//	this->savedMouseCoords.y - this->selectOffset.y
			//);
		//}

		this->blobColl->move(dt);
		this->blobColl->sc(*(this->env));
		this->blobColl->setForce(this->gravity);
	}

	void Control::init()
	{
		this->stopped = false;
		this->timeout();
		/*
		while (true)
		{
			// stop 100% cpu
			PA_WaitForVBL();
		}
		*/
	}
}
